﻿using System;
using System.Diagnostics;
using System.Threading;

namespace ExtensionsPerformanceTests
{
    /// <summary>
    /// Stupid class to measure performance in the console
    /// </summary>
    public class Chrono : IDisposable
    {
        private static int ChronoCount = 1;

        private readonly ILogProvider logProvider;
        private readonly string name;
        private readonly Stopwatch stopwatch;


        public Chrono()
            : this( "Choro_" + Interlocked.Increment( ref ChronoCount ) )
        {
            //Note: no initialization here, because it affects performance measure
        }


        public Chrono( string name )
            : this( name, new ConsoleLogProvider() )
        {
            //Note: no initialization here, because it affects performance measure
        }

        public Chrono( string name, ILogProvider logProvider )
        {
            this.name = name;
            this.logProvider = logProvider;

            stopwatch = new Stopwatch();
            stopwatch.Start();
        }

        #region IDisposable Members

        public void Dispose()
        {
            stopwatch.Stop();

            logProvider.LogLine( name + ": " );
            logProvider.LogLine( "Ticks: " + stopwatch.ElapsedTicks );
            logProvider.LogLine( "Milliseconds: " + stopwatch.ElapsedMilliseconds );
            logProvider.LogLine( string.Empty );
        }

        #endregion
    }

    public interface ILogProvider
    {
        void Log( string message );
    }

    public static class LogProviderExtensions
    {
        public static void LogLine( this ILogProvider source, string message )
        {
            source.Log( message + Environment.NewLine );
        }
    }

    public class ConsoleLogProvider : ILogProvider
    {
        #region ILogProvider Members

        public void Log( string message )
        {
            Console.Write( message );
        }

        #endregion
    }
}